package com.newland.server.controller;

import com.newland.server.model.SysUser;
import com.newland.server.service.SysUserService;
import com.newland.server.utils.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("sysuser")
public class SysUserController {
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private SysUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 注册用户
     *
     * @param user
     * @return
     */
    @PostMapping("register")
    @RequiresPermissions("sysuser/register")
    public AjaxResponse register(@RequestBody SysUser user) {
        try {
            userService.saveUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResponse.error(new CustomException(CustomExceptionType.OTHER_ERROR, e.getMessage()));
        }
        return AjaxResponse.success();
    }

    /**
     * 用户登录，使用用户主身份换取token
     *
     * @param map
     * @return
     */
    @PostMapping("login")
    public AjaxResponse login(@RequestBody Map<String, String> map) {
        String username = map.get(jwtProperties.getPrincipal());
        String password = map.get(jwtProperties.getPassword());
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "用户名或密码不能为空"));
        }
        SysUser user = userService.findUser(username);
        if(null==user){
            return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "未知用户"));
        }else{
            if(!password.equals(user.getPwd())){
                return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "密码错误"));
            }

        }
        long currentTimeMillis = System.currentTimeMillis();//这是当前的时间戳
        String token = jwtTokenUtil.generateToken(username,currentTimeMillis);//保存生成token的时间戳
        stringRedisTemplate.opsForValue().set(username,String.valueOf(currentTimeMillis),jwtProperties.getRedisexpiration(), TimeUnit.MILLISECONDS);//当前登录用户名和当前时间戳作为键值对保存在redis中
        return AjaxResponse.success(token);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("logout")
    @RequiresAuthentication
    public AjaxResponse logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return AjaxResponse.success();
    }
}
